/**
 * 
 */
package io.potato.core.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * rest接口返回数据封装
 * @author timl
 *
 */
public class RestEntity {
	
	private static RestEntity okEntity = new RestEntity("ok");
	
	static ObjectMapper objectMapper = new ObjectMapper();
	
	/**
	 * 返回成功
	 * @return
	 */
	public static RestEntity ok() {
		return okEntity;
	}
	
	/**
	 * 返回成功和数据
	 * @param data 要返回的数据
	 * @return
	 */
	public static RestEntity ok(Object data) {
		RestEntity restEntity = new RestEntity(data);
		return restEntity;
	}
	
	/**
	 * 返回错误信息
	 * @param code  错误代码
	 * @param message  错误信息
	 * @return
	 */
	public static RestEntity error(int code, String message) {
		return new RestEntity(code, message);
	}
	
	/**
	 * 返回错误信息
	 * @param error  错误对象
	 * @return
	 */
	public static RestEntity error(ErrorMessage error) {
		return new RestEntity(error);
	}
	
	public RestEntity(Object data) {
		this.setData(data);
		this.setSuccess(true);
	}
	
	public RestEntity(int code, String message) {
		this.setData(null);
		this.setSuccess(false);
		this.setError(new ErrorMessage(code, message));
	}
	
	public RestEntity(ErrorMessage error) {
		this.setData(null);
		this.setSuccess(false);
		this.setError(error);
	}
	
	public String toJsonString() {
		try {
			return objectMapper.writeValueAsString(this);
		} catch (JsonProcessingException e) {
			return this.toString();
		}
	}
	
	/**
	 * 是否成功
	 */
	private boolean success;
	
	/**
	 * 返回的数据，一般成功才有
	 */
	private Object data;
	
	/**
	 * 错误信息
	 */
	private ErrorMessage error;
	
	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}
	
	public ErrorMessage getError() {
		return error;
	}

	public void setError(ErrorMessage error) {
		this.error = error;
	}
	
}
